package com.piaoniu.open.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Function;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author: daniel
 * @creed: keep it simple and stupid !
 * @Time: 2019/6/12 11:52 AM
 */
@Slf4j
public class MapUtils {

    public static Function<Object, String> getStringConverter(Object value) {

        Class<?> fieldClass = value.getClass();
        //基础类型
        if (fieldClass.isPrimitive()) {
            return e -> String.valueOf(e);
        }

        if (value instanceof List) {
            return e -> {
                List list = (List) e;
                return StringUtils.join(list, ",");
            };
        }

        return e -> e.toString();
    }


    //获取所有的field getter
    //toString
    public static Map<String, String> objectToStringMap(Object object) {
        Map<Field, Method> fieldGetters = ReflectionUtils.getFieldGetters(object.getClass());

        Map<String, String> result = new HashMap<>();
        for (Map.Entry<Field, Method> fieldGetter : fieldGetters.entrySet()) {
            Method method = fieldGetter.getValue();
            Field field = fieldGetter.getKey();
            try {
                Object value = method.invoke(object, new Object[]{});
                String stringValue = getStringConverter(value).apply(value);
                result.put(field.getName(), stringValue);

            } catch (Exception e) {
                log.warn("objectToStringMap failed : {}", ExceptionUtils.flatStackToString(e));
            }
        }
        return result;
    }
}
